package com.bjsxt.shop.head.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bjsxt.shop.common.controller.BaseController;
import com.bjsxt.shop.common.util.ConstatFinalUtil;
import com.bjsxt.shop.common.util.PageInfoUtil;
import com.bjsxt.shop.goods.pojo.AGoods;
import com.bjsxt.shop.goods.pojo.AGoodsEnum;
import com.bjsxt.shop.goods.service.IGoodsService;
import com.bjsxt.shop.users.pojo.AUsers;
import com.bjsxt.shop.users.pojo.AUsersCar;
import com.bjsxt.shop.users.service.IUsersService;

/**
 * 不需要登陆就可以访问的页面
 * @author wangshSxt
 *
 */
@Controller
public class GoodsHeadController extends BaseController
{
	@Resource
	private IGoodsService goodsService;
	@Resource
	private IUsersService usersService;
	
	/**
	 * 商品列表页面
	 * @return
	 */
	@RequestMapping("/goods")
	public String goodsList(HttpServletRequest request)
	{
		ConstatFinalUtil.LOGGER.info("---goodsList--request--");
		return this.goodsList(request,"1");
	}
	
	/**
	 * 商品列表页面
	 * @return
	 */
	@RequestMapping("/goods_{currentPage}")
	public String goodsList(HttpServletRequest request,@PathVariable String currentPage)
	{
		ConstatFinalUtil.LOGGER.info("---goodsList--request--currentPage--");
		PageInfoUtil pageInfoUtil = this.proccedPageInfo(currentPage,ConstatFinalUtil.BUNDLE.getString("head.pageSize.image"));
		
		/* 按照条件查询数据 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("status", AGoodsEnum.STATUS_ENABLE.getStatus());
		/* 查询数据 */
		List<AGoods> goodsList = this.goodsService.findCondListGoodsService(pageInfoUtil, condMap);
		/* 存储结果 */
		request.setAttribute("goodsList", goodsList);
		request.setAttribute("pageInfoUtil", pageInfoUtil);
		request.setAttribute("websitePath", ConstatFinalUtil.BUNDLE.getString("website.path"));
		return "/head/goodsList" ; 
	}
	
	/**
	 * 商品详情
	 * @return
	 */
	@RequestMapping("/goods/{gid}")
	public String goodsInfo(HttpServletRequest request , @PathVariable String gid)
	{
		ConstatFinalUtil.LOGGER.info("---- goodsInfo ----");
		/* 根据Id查询商品详情 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("id", gid);
		AGoods goods = this.goodsService.findOneGoodsService(condMap);
		/* 存储request */
		request.setAttribute("goods", goods);
		return "/head/goodsInfo" ; 
	}
	
	/** 
	 * 购物车列表
	 * [
	 * 	{'id':'12','num':'5'},
	 * 	{'id':'1','num':'2'}
	 * ]
	 * @return
	 */
	@RequestMapping("/shopCarList")
	public String shopCarList(HttpServletRequest request)
	{
		ConstatFinalUtil.LOGGER.info("--shopCarList--");
		/* 判断是否登陆 */
		HttpSession session = request.getSession() ;
		AUsers users = (AUsers) session.getAttribute("users");
		
		JSONArray shopCarArr = new JSONArray() ; 
		Map<String, Object> condMap = new HashMap<String,Object>() ;
		if(users != null)
		{
			/* 从数据库查询购物车 */
			condMap.put("usersId", users.getId());
			List<AUsersCar> usersCarList = this.usersService.findCondListUsersCarService(null, condMap);
			for (Iterator iterator = usersCarList.iterator(); iterator.hasNext();)
			{
				AUsersCar usersCar = (AUsersCar) iterator.next();
				AGoods goods = usersCar.getGoods();
				
				JSONObject json = new JSONObject() ; 
				json.put("id", usersCar.getId());
				json.put("name", goods.getName());
				json.put("price", goods.getPrice() + "");
				json.put("remainNumStr", goods.getRemainNumStr());
				json.put("img", goods.getListImgPath());
				json.put("num", usersCar.getNum());
				shopCarArr.add(json);
			}
		}else
		{
			/* 从Cookie中查询购物车 */
			shopCarArr = shopCarListCookie(request);
		}
		
		/* 接收gid,表示新添加的端口 */
		String gid = request.getParameter("gid");
		if(gid == null)
		{
			gid = "" ; 
		}
		
		if(!"".equalsIgnoreCase(gid))
		{
			/* 根据ID查询商品 */
			condMap.clear();
			condMap.put("id", gid);
			AGoods goods = this.goodsService.findOneGoodsService(condMap);
			request.setAttribute("goods", goods);
		}
		
		/* 存储结果 */
		request.setAttribute("shopCarArr", shopCarArr);
		request.setAttribute("websitePath", ConstatFinalUtil.BUNDLE.getString("website.path"));
		return "/head/shopCarList" ; 
	}
	
	/**
	 * 未登陆,取Cookie的购物车
	 * @param request
	 * @return
	 */
	private JSONArray shopCarListCookie(HttpServletRequest request)
	{
		String shopCarListStr = "[]" ; 
		/* 从Cookie中取数据 */
		Cookie[] cookies = request.getCookies();
		if(cookies != null)
		{
			for (int i = 0; i < cookies.length; i++)
			{
				Cookie cookieTemp = cookies[i];
				if("shopCarList".equalsIgnoreCase(cookieTemp.getName()))
				{
					/* 购物车的JSON数据 */
					shopCarListStr = cookieTemp.getValue() ; 
					break ; 
				}
			}
		}
		/* 将Cookie的数据转换成JSON对象 */
		JSONArray shopCarArr = JSON.parseArray(shopCarListStr);
		
		Map<String, Object> condMap = new HashMap<String, Object>();
		for (Iterator iterator = shopCarArr.iterator(); iterator.hasNext();)
		{
			JSONObject json = (JSONObject) iterator.next();
			String gid = json.getString("id");
			String num = json.getString("num");
			
			/* 根据ID查询商品 */
			condMap.clear();
			condMap.put("id", gid);
			AGoods goods = this.goodsService.findOneGoodsService(condMap);
			json.put("id", "0");
			json.put("name", goods.getName());
			json.put("price", goods.getPrice() + "");
			json.put("remainNumStr", goods.getRemainNumStr());
			json.put("img", goods.getListImgPath());
		}
		return shopCarArr;
	}
	
	/**
	 * 购物车列表
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping("/shopCarInsertSubmit")
	public String shopCarInsertSubmit(HttpServletRequest request,HttpServletResponse response,String gid) throws Exception
	{
		ConstatFinalUtil.LOGGER.info("--shopCarInsertSubmit--");
		/* 判断是否登陆 */
		HttpSession session = request.getSession() ;
		AUsers users = (AUsers) session.getAttribute("users");
		Map<String, Object> condMap = new HashMap<String,Object>() ;
		if(users != null)
		{
			/* 商品数量 */
			String numStr = request.getParameter("num");
			if(numStr == null)
			{
				numStr = "" ; 
			}
			
			if("".equalsIgnoreCase(numStr))
			{
				numStr = "1" ; 
			}
			
			/* 已登陆直接入库 */
			condMap.clear();
			condMap.put("usersId", users.getId());
			condMap.put("goodsId", gid);
			AUsersCar usersCar = this.usersService.findOneUsersCarService(condMap);
			
			boolean flag = true ; 
			if(usersCar == null)
			{
				usersCar = new AUsersCar();
				usersCar.setGoodsId(Integer.valueOf(gid));
				usersCar.setUsersId(users.getId());
				usersCar.setNum(Integer.valueOf(numStr));
				usersCar.setStatus(Byte.valueOf("1"));
				usersCar.setCreateTime(new Date());
				flag = false ; 
			}else
			{
				/* 同一个用户,同一个商品,数据库的购物车已经存在,应该拿老的数量+新的数量 */
				usersCar.setNum(usersCar.getNum() + Integer.valueOf(numStr));
			}
			
			usersCar.setUpdateTime(new Date());
			usersCar.setPubTime(new Date());
			
			if(flag)
			{
				this.usersService.updateOneUsersCarService(usersCar);
			}else
			{
				this.usersService.saveOneUsersCarService(usersCar);
			}
		}else
		{
			/* 未登陆,Cookie操作 */
			shopCarInsertCookie(request, response, gid);
		}
		return "redirect:/shopCarList.htm?gid=" + gid ; 
	}

	/**
	 * 未登陆,添加购物车,操作Cookie
	 * 
	 * @param request
	 * @param response
	 * @param gid
	 * @throws InterruptedException
	 */
	private void shopCarInsertCookie(HttpServletRequest request, HttpServletResponse response, String gid)
			throws InterruptedException
	{
		/* 商品数量 */
		String numStr = request.getParameter("num");
		if(numStr == null)
		{
			numStr = "" ; 
		}
		
		if("".equalsIgnoreCase(numStr))
		{
			numStr = "1" ; 
		}
		
		String shopCarListStr = "[]" ; 
		/* 从Cookie中取数据 */
		Cookie[] cookies = request.getCookies();
		if(cookies != null)
		{
			for (int i = 0; i < cookies.length; i++)
			{
				Cookie cookieTemp = cookies[i];
				if("shopCarList".equalsIgnoreCase(cookieTemp.getName()))
				{
					/* 购物车的JSON数据 */
					shopCarListStr = cookieTemp.getValue() ; 
					break ; 
				}
			}
		}
		JSONArray shopCarArr = JSON.parseArray(shopCarListStr);
		/* 将商品id和数量添加到json中,
		 * 循环json,判断商品是否存在
		 *  */
		JSONObject goodsJSON = new JSONObject() ; 
		
		boolean flag = false ; 
		for (Iterator iterator = shopCarArr.iterator(); iterator.hasNext();)
		{
			JSONObject json = (JSONObject) iterator.next();
			if(gid.equalsIgnoreCase(json.getString("id")))
			{
				/* 数量+1 */
				int num = Integer.valueOf(json.get("num") + "") + Integer.valueOf(numStr);
				json.put("num", num + "") ;
				flag = true ; 
				break ; 
			}
		}
		
		/* 找不到商品Id,新增加的商品,添加到购物车的json中 */
		if(!flag)
		{
			goodsJSON.put("id", gid);
			goodsJSON.put("num", numStr);
			shopCarArr.add(goodsJSON);
		}
		
		/* 将json存储Cookie中 */
		Cookie cookie = new Cookie("shopCarList", shopCarArr.toJSONString());
		cookie.setPath(request.getContextPath());
		cookie.setMaxAge(-1);
		response.addCookie(cookie);
		Thread.sleep(50);
	}
}
